package com.demo.spring.system.service.impl;

import java.io.IOException;
import java.io.InputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.demo.spring.system.service.HdfsService;
import com.demo.spring.utils.HDFSUtil;

@Service
public class HdfsServiceImpl implements HdfsService {

	@Autowired
	FileSystem hFileSystem;
	
	@Override
	public boolean uploadFile(String filePath, byte[] datas) throws IOException {
		
		if(HDFSUtil.exits(hFileSystem, filePath)){
			StringUtils.getFilename(filePath);
			filePath  = filePath.substring(0, filePath.lastIndexOf("."))+"."+System.currentTimeMillis()+"."+StringUtils.getFilenameExtension(filePath);
		}
		
		return HDFSUtil.createFile(hFileSystem, filePath, datas);
	}

	@Override
	public InputStream downloadFile(String filePath) throws IOException {
		Path path = new Path(filePath);
		if (hFileSystem.exists(path)) {
			return hFileSystem.open(path);
		}
		return null;
	}

	@Override
	public boolean deleteFileFromHDFS(String filePath) throws IOException {
		return HDFSUtil.deleteFile(hFileSystem, filePath, true);
	}

	@Override
	public FileStatus[] getSubDirFileStatus(String dirPath) throws IOException {
		FileStatus[] fileStatus = HDFSUtil.listStatus(hFileSystem, dirPath);
		return fileStatus;
	}

}
